package com.iot.web.controller.device;

import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.iot.common.utils.DateUtils;
import com.iot.common.utils.uuid.IdUtils;
import com.iot.device.domain.PressureSensorParam;
import com.iot.device.service.IPressureSensorParamService;
import com.iot.mqtt.callback.PressureSensorClientMqttCallback;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.iot.common.annotation.Log;
import com.iot.common.core.controller.BaseController;
import com.iot.common.core.domain.AjaxResult;
import com.iot.common.enums.BusinessType;
import com.iot.device.domain.PressureSensorClient;
import com.iot.device.service.IPressureSensorClientService;
import com.iot.common.utils.poi.ExcelUtil;
import com.iot.common.core.page.TableDataInfo;

/**
 * 压力传感器设备Controller
 *
 * @author iot
 * @date 2023-06-30
 */
@RestController
@RequestMapping("/device/pressureSensorClient")
public class PressureSensorClientController extends BaseController
{
    @Autowired
    private IPressureSensorClientService pressureSensorClientService;
    @Autowired
    private IPressureSensorParamService pressureSensorParamService;
    @Autowired
    private PressureSensorClientMqttCallback pressureSensorClientMqttCallback;

    /**
     * 查询压力传感器设备列表
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:list')")
    @GetMapping("/list")
    public TableDataInfo list(PressureSensorClient pressureSensorClient)
    {
        startPage();
        List<PressureSensorClient> list = pressureSensorClientService.selectPressureSensorClientList(pressureSensorClient);
        return getDataTable(list);
    }

    /**
     * 导出压力传感器设备列表
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:export')")
    @Log(title = "压力传感器设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PressureSensorClient pressureSensorClient)
    {
        List<PressureSensorClient> list = pressureSensorClientService.selectPressureSensorClientList(pressureSensorClient);
        ExcelUtil<PressureSensorClient> util = new ExcelUtil<PressureSensorClient>(PressureSensorClient.class);
        util.exportExcel(response, list, "压力传感器设备数据");
    }

    /**
     * 获取压力传感器设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(pressureSensorClientService.selectPressureSensorClientById(id));
    }

    /**
     * 新增压力传感器设备
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:add')")
    @Log(title = "压力传感器设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PressureSensorClient pressureSensorClient)
    {
        return toAjax(pressureSensorClientService.insertPressureSensorClient(pressureSensorClient));
    }

    /**
     * 修改压力传感器设备
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:edit')")
    @Log(title = "压力传感器设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PressureSensorClient pressureSensorClient)
    {
        return toAjax(pressureSensorClientService.updatePressureSensorClient(pressureSensorClient));
    }

    /**
     * 删除压力传感器设备
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:remove')")
    @Log(title = "压力传感器设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pressureSensorClientService.deletePressureSensorClientByIds(ids));
    }

    /**
     * 获取压力传感器设备参数信息
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:query')")
    @GetMapping(value = "/pressureSensorParamBySn/{sn}")
    public AjaxResult pressureSensorParamBySn(@PathVariable("sn") String sn)
    {
        /*{
            "devtype": "ch4_alarmer",
            "seq":"3884",
            "ts": "1661843863006"
        }*/
        PressureSensorParam pressureSensorParam = pressureSensorParamService.pressureSensorParamBySn(sn);
        if(pressureSensorParam == null){
            // 如果没有参数，返回new对象，并对设备下发call读参命令
            PressureSensorClient pressureSensorClient = pressureSensorClientService.selectPressureSensorClientBySn(sn);
            JSONObject data = new JSONObject();
            data.put("devtype", pressureSensorClient.getDevtype());
            data.put("seq", IdUtils.fastSimpleUUID().substring(0, 5));
            data.put("ts", DateUtils.getTimestamp());
            pressureSensorClientMqttCallback.publish(PressureSensorClientMqttCallback.fillTopic(PressureSensorClientMqttCallback.CLOUD_TOPIC_CALL, pressureSensorClient.getPkey(), sn), 2, data.toJSONString());
            pressureSensorParam = new PressureSensorParam();
        }
        return AjaxResult.success(pressureSensorParam);
    }

    /**
     * 压力传感器设备设置参数
     */
    @PreAuthorize("@ss.hasPermi('device:pressureSensorClient:setParam')")
    @Log(title = "压力传感器设备", businessType = BusinessType.OTHER)
    @PostMapping("/setParam/{pKey}/{sn}")
    public AjaxResult setParam(@PathVariable String pKey, @PathVariable String sn, @RequestBody JSONObject param)
    {
        /*{
            "devtype": "ch4_alarmer",
            "seq": "A3889",
            "parameter": {
                "Mode": "0",
                "Dc ": "0",
                "longitude ": "0.0",
                "latitude ": "0.0"
            },
            "payload": {
                "HHLimitAlarm": "250",
                "HLimitAlarm": "245",
                "LLLimitAlarm": "0",
                "LLimitAlarm": "5",
                "RangeL": "0",
                "RangeH": "2500",
                "solenoidValveOnOff ": "0"
            },
            "ts": "1661843863006"
        }*/
        PressureSensorClient pressureSensorClient = pressureSensorClientService.selectPressureSensorClientBySn(sn);
        JSONObject data = new JSONObject();
        data.put("devtype", pressureSensorClient.getDevtype());
        data.put("seq", IdUtils.fastSimpleUUID().substring(0, 5));
        data.put("ts", DateUtils.getTimestamp());
        JSONObject parameter = new JSONObject();
        parameter.put("mode", param.getInteger("mode"));
        parameter.put("dc", param.getInteger("dc"));
        parameter.put("ntpOrNot", param.getInteger("ntpOrNot"));
        data.put("parameter", parameter);
        JSONObject payload = new JSONObject();
        payload.put("hHLimitAlarm", param.getLong("limitAlarmHh"));
        payload.put("hLimitAlarm", param.getLong("limitAlarmH"));
        payload.put("lLimitAlarm", param.getLong("limitAlarmL"));
        payload.put("lLLimitAlarm", param.getLong("limitAlarmLl"));
        payload.put("rangeL", param.getLong("rangeL"));
        payload.put("rangeH", param.getLong("rangeH"));
        payload.put("solenoidValveOnOff", param.getLong("solenoidValveOnOff"));
        data.put("payload", payload);
//        System.out.println(data.toJSONString());
        pressureSensorClientMqttCallback.publish(PressureSensorClientMqttCallback.fillTopic(PressureSensorClientMqttCallback.CLOUD_TOPIC_SET, pKey, sn), 2, data.toJSONString());
        return AjaxResult.success();
    }

    /**
     * 获取压力传感器设备参数信息
     */
    @GetMapping(value = "/pressureSensorEarthquakeDrill/{sn}")
    public AjaxResult pressureSensorEarthquakeDrill(@PathVariable("sn") String sn, @RequestParam("second") int second, @RequestParam("second") int intensity)
    {
        /*
            主题：clientNo/earthquakeWarningDril
            例：0224310202307080/earthquakeWarningDril
            字段："1"-倒计时，单位秒，
            "2"-地震烈度
            例：{"1":"10","2":"5"}
        * */
        JSONObject data = new JSONObject();
        data.put("1", second);
        data.put("2", intensity);
        pressureSensorClientMqttCallback.publish(PressureSensorClientMqttCallback.EARTHQUAKE_DRILL.replace("${sn}", sn), 2, data.toJSONString());
        return AjaxResult.success();
    }

    /**
     * （测试）获取压力传感器设备参数信息
     */
    @GetMapping(value = "/pressureSensorEarthquakeDrillTest/{sn}")
    public AjaxResult pressureSensorEarthquakeDrillTest(@PathVariable("sn") String sn, @RequestParam("second") int second, @RequestParam("second") int intensity)
    {
        /*
            主题：clientNo/earthquakeWarningDril
            例：0224310202307080/earthquakeWarningDril
            字段："1"-倒计时，单位秒，
            "2"-地震烈度
            例：{"1":"10","2":"5"}
        * */
        JSONObject data = new JSONObject();
        data.put("1", second);
        data.put("2", intensity);
        pressureSensorClientMqttCallback.publish(PressureSensorClientMqttCallback.EARTHQUAKE_DRILL.replace("${sn}", sn), 2, data.toJSONString());
        return AjaxResult.success();
    }
}
